package org.example.data.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.data.entity.*;
import org.example.data.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Iterator;

@Slf4j
@Service
public class ImportGonghuiData {

    @Autowired
    private UAccountMapper uAccountMapper;

    @Autowired
    private TUnionLaborMapper tUnionLaborMapper;

    @Autowired
    private UAccountAuthenMapper uAccountAuthenMapper;

    @Autowired
    private TUnionLaborMemberMapper tUnionLaborMemberMapper;
    @Autowired
    private UMemberShipMapper uMemberShipMapper;
    @Autowired
    private UOrganizationMapper uOrganizationMapper;

    public void importData() {
        FileInputStream file = null;
        try {
            file = new FileInputStream(ResourceUtils.getFile("classpath:data.xlsx"));
            //file = new FileInputStream("data.xlsx");
            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook wb = new XSSFWorkbook(file);

            XSSFSheet ws = wb.getSheetAt(0);
            for (Row row : ws) {
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType()) {
                        case NUMERIC:
                            System.out.print(cell.getNumericCellValue());
                            break;
                        case STRING:
                            System.out.print(cell.getStringCellValue());
                            break;
                    }
                }
                System.out.println("Reading File Completed.");
            }
            file.close();
        } catch (IOException e) {
            //log.error();
            throw new RuntimeException(e);
        }
    }

    @Transactional
    public void importGonghuiData() {
        FileInputStream file = null;
        try {
            file = new FileInputStream(ResourceUtils.getFile("classpath:data.xlsx"));
            //file = new FileInputStream("data.xlsx");
            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook wb = new XSSFWorkbook(file);

            XSSFSheet ws = wb.getSheetAt(0);
            for (Row row : ws) {
                if (row.getRowNum() == 0) {//跳过表头
                    continue;
                }
                log.info("第{}号{}的信息开始导入",row.getRowNum(),row.getCell(0).getStringCellValue());
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();

                String name = row.getCell(0).getStringCellValue(); //姓名
                String sex = row.getCell(1).getStringCellValue(); //性别
                String idCardNum = row.getCell(3).getStringCellValue(); //身份证号码
                String phone = row.getCell(7).getStringCellValue(); //手机号
                String gonghuiName = row.getCell(17).getStringCellValue(); //工会名称
                String danweiName = row.getCell(18).getStringCellValue(); //单位名称

                log.info("数据: name={},sex={},idCardNum={},phone={},gonghuiName={},danweiName={}",name,sex,idCardNum,phone,gonghuiName,danweiName);
                //导入逻辑
                //查找工会
                TUnionLabor tUnionLabor = tUnionLaborMapper.selectOne(Wrappers.<TUnionLabor>lambdaQuery().eq(TUnionLabor::getName, gonghuiName.trim()));
                if (tUnionLabor == null) {
                    log.error("查不到所在工会:{}",gonghuiName);
                    throw new RuntimeException();
                }
                UAccount uAccount = new UAccount();
                uAccount.setUsername(name);
                uAccount.setIsEnable(1);
                uAccount.setIsDelete(0);
                uAccount.setUnionLaborId(tUnionLabor.getId().intValue());//工会id
                uAccount.setCreateTime(LocalDateTime.now());
                uAccount.setUpdateTime(LocalDateTime.now());
                int insert = uAccountMapper.insert(uAccount);//插入账号

                //插入权限
                addAuthen(idCardNum, idCardNum, uAccount);
                addAuthen(idCardNum, phone, uAccount);
                //插入会员关系 u_membership
                UOrganization uOrganization = uOrganizationMapper.selectOne(Wrappers.<UOrganization>lambdaQuery().eq(UOrganization::getOrganizationName, danweiName));
                addMemberShip(uAccount,uOrganization.getId());
                //插入工会关系 u_union_labor_member
                TUnionLaborMember tUnionLaborMember = new TUnionLaborMember();
                tUnionLaborMember.setUnionLaborId(tUnionLabor.getId().intValue());
                tUnionLaborMember.setName(uAccount.getUsername());
                tUnionLaborMember.setIdNo(idCardNum);
                tUnionLaborMember.setPhone(phone);
                tUnionLaborMember.setCheckState(1);
                tUnionLaborMember.setAccountId(uAccount.getId());
                tUnionLaborMember.setRegisterSource(2);
                tUnionLaborMemberMapper.insert(tUnionLaborMember);

            }
            file.close();
            log.info("-----插入完毕------");
        } catch (IOException e) {
            //log.error();
            throw new RuntimeException(e);
        }
    }

    private void addMemberShip(UAccount uAccount,Integer orgId) {
        UMemberShip uMemberShip = new UMemberShip();
        uMemberShip.setAccountId(uAccount.getId());
        uMemberShip.setRoleId(7);
        uMemberShip.setOrganizationId(orgId);
        uMemberShip.setDepartmentId(5);
        uMemberShip.setDutyId(1);
        uMemberShip.setIsMine(1);
        uMemberShip.setCombineStr(orgId+"_5_1");
        uMemberShipMapper.insert(uMemberShip);
    }

    private void addAuthen(String idCardNum, String phone, UAccount uAccount) {
        UAccountAuthen authen2 = new UAccountAuthen();
        authen2.setType("p");
        authen2.setLoginInputName(idCardNum);
        authen2.setLoginName(DigestUtils.md5DigestAsHex(phone.getBytes()));
        authen2.setLoginPwd("5f0c2682065376c531b4d4aa6d582ec4");
        authen2.setAccountId(uAccount.getId());
        authen2.setRegisterTime(LocalDateTime.now());
        authen2.setUpdateTime(LocalDateTime.now());
        authen2.setCreateTime(LocalDateTime.now());
        uAccountAuthenMapper.insert(authen2);
    }
}
